package com.zdxf.util;

import com.alibaba.druid.util.StringUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class CsvUtil {
    public static List<String> readCsv(String filename) {
        // 字符编码
        Charset charset = StandardCharsets.UTF_8;
        // 缓存大小 提高读取效率
        int bufferSize = 5 * 1024 * 1024;
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(filename), charset), bufferSize)) {
            String line;
            List<String> data = new ArrayList<>();
            // 这里假设文件不是很大，不然这么些内存是不够用的
            while (Objects.nonNull(line = reader.readLine())) {
                data.add(line);
            }
            return data;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> writeCsv(String filename, List<String> data) {
        // 文件路径和文件名
        String file = filename;
        // 指定字符编码
        Charset charset = StandardCharsets.UTF_8;
        // 指定缓存
        int bufferSize = 5 * 1024 * 1024;
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file), charset), bufferSize
        )) {
            for (String line : data) {
                if (!StringUtils.isEmpty(line)) {
                    writer.write(line);
                    writer.newLine();
                }
            }
            writer.close();
            return data;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
